<script setup>
import { ref } from 'vue'
import useAuthStore from '@/store/auth'
import { APP_NAME, HOME_URL } from '@/config'
import api from '@/api'
import { useRouter, useRoute } from 'vue-router'

const authStore = useAuthStore()
const $router = useRouter()
const $route = useRoute()

// 已登录则跳转首页
if (authStore.isLogin()) {
  $router.push($route.query.redirect || '/')
}

const formData = ref({
  username: '',
  password: '',
})

const loading = ref(false)

const formSubmit = async ({ values, errors }) => {
  if (errors) {
    return
  }

  loading.value = true

  try {
    const data = await api.post('/auth/login', values)
    authStore.login(data)
    $router.push($route.query.redirect || HOME_URL)
  } catch (_) {}

  loading.value = false
}
</script>

<template>
  <div class="page-login">
    <a-form class="login-form" :model="formData" @submit="formSubmit">
      <div class="title">{{ APP_NAME }}</div>
      <div class="subtitle"></div>
      <a-form-item
        hide-label
        field="username"
        :rules="[{ required: true, message: '请输入账号' }]"
      >
        <a-input
          v-model="formData.username"
          placeholder="请输入账号"
          allow-clear
        >
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        hide-label
        field="password"
        :rules="[{ required: true, message: '请输入密码' }]"
      >
        <a-input-password
          v-model="formData.password"
          placeholder="请输入密码"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-button html-type="submit" type="primary" long :loading="loading"
        >登录</a-button
      >
    </a-form>
  </div>
</template>

<style scoped>
.page-login {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-form {
  width: 400px;
}

.title {
  color: #1d2129;
  font-size: 22px;
  text-align: center;
}

.subtitle {
  color: #86909c;
  font-size: 16px;
  margin: 15px 0;
  text-align: center;
}
</style>
